//
//  EpisodeAPI.swift
//  WBDemo
//
//  Created by Jin on 26/04/2018.
//  Copyright © 2018 com.baidu.123. All rights reserved.
//

import Foundation

struct Episodes:Codable {
    
    struct EpisodeInfo:CodingKey {
        var stringValue: String
        var intValue: Int? { return nil } //intValue用不到,直接返回nil
        
        init?(intValue: Int) {
            return nil
        }
        
        init?(stringValue: String) {
            self.stringValue = stringValue
        }
        
        static let title = EpisodeInfo(stringValue: "title")!
    }
    
    var episodes: [EpisodeKeys] = []
    
    //编码
    func encode(to encoder:Encoder) throws {
        var container = encoder.container(keyedBy: EpisodeInfo.self)
        
        try episodes.forEach { (episodeKeys) in
            let id = EpisodeInfo(stringValue: String(episodeKeys.id))!
            var inner = container.nestedContainer(keyedBy: EpisodeInfo.self, forKey: id)
            try inner.encode(episodeKeys.title, forKey: .title)
        }
    }
    
    
    //解码
    init(from decoder:Decoder) throws {
        let container = try decoder.container(keyedBy: EpisodeInfo.self)
        var v = [EpisodeKeys]()
        
        try container.allKeys.forEach{
            let inner = try container.nestedContainer(keyedBy: EpisodeInfo.self, forKey: $0)
            let title = try inner.decode(String.self, forKey: .title)
            v.append(EpisodeKeys(id: Int($0.stringValue)!, title: title))
        }
        
        self.episodes = v
    }
}

struct EpisodeKeys: Codable {
    let id:Int
    let title:String
}


